package mips.instructions;

/**
 * <code>TGEU</code> instruction<br/>
 * Trap Greater Than Or Equal Unsigned<br/>
 * @author jnmartin84@gmail.com
 */
public class TGEU extends Instruction {

	private static final String INSTRUCTION_NAME = "TGEU";
	private static final TGEU INSTANCE = new TGEU();

	private TGEU(){}

	public static final TGEU getInstance() {
		return INSTANCE;
	}

	/**
	 * <b>Format:</b><br/>
	 * TGEU rs, rt<br/><br/>
	 * <b>Description:</b><br/>
	 * The contents of general register rt are compared to the contents of general<br/>
	 * register rs. Considering both quantities as unsigned integers, if the<br/>
	 * contents of general register rs are greater than or equal to the contents of<br/>
	 * general register rt, a trap exception occurs.<br/><br/>
	 * The code field is available for use as software parameters, but is retrieved<br/>
	 * by the exception handler only by loading the contents of the memory word<br/>
	 * containing the instruction.<br/><br/>
	 * <b>Operation:</b><br/>
	 * T: if (0 || GPR[rs]) &ge; (0 || GPR[rt]) then<br/>
	 * TrapException<br/>
	 * endif<br/>
	 * @throws mips.exceptions.TrapException
	 */
	@Override
	public final void execute(final int instruction) throws mips.exceptions.TrapException {

		mips.instructions.Instruction.RS = (instruction >> 21) & 0x0000001F;
		mips.instructions.Instruction.RT = (instruction >> 16) & 0x0000001F;

		final long u32_gpr_rs = mips.instructions.Instruction.zeroExtendW(mips.R4300i.GPR[mips.instructions.Instruction.RS]);
		final long u32_gpr_rt = mips.instructions.Instruction.zeroExtendW(mips.R4300i.GPR[mips.instructions.Instruction.RT]);

		if(u32_gpr_rs >= u32_gpr_rt) {
			throw new mips.exceptions.TrapException(mips.R4300i.PC,instruction);
		}

		mips.R4300i.PC = mips.R4300i.nPC;
		mips.R4300i.nPC = mips.R4300i.PC + 4;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String emit(final int instruction) {

		mips.instructions.Instruction.RS = (instruction >> 21) & 0x0000001F;
		mips.instructions.Instruction.RT = (instruction >> 16) & 0x0000001F;

		return	"		u32_gpr_rs = mips.instructions.Instruction.zeroExtendW(mips.CPU.GPR["+mips.instructions.Instruction.RS+"]);\n" +
				"		u32_gpr_rt = mips.instructions.Instruction.zeroExtendW(mips.CPU.GPR["+mips.instructions.Instruction.RT+"]);\n" +
				"		\n" +
				"		if(u32_gpr_rs >= u32_gpr_rt) {\n" +
				"			throw new mips.exceptions.TrapException(mips.CPU.PC,"+String.format("0x%08X",instruction)+");\n" +
				"		}\n" +
				"		\n" +
				"		mips.CPU.PC = mips.CPU.nPC;\n" +
				"		mips.CPU.nPC = mips.CPU.PC + 4;\n";
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName(final int instruction) {
		return getName();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName() {
		return INSTRUCTION_NAME;
	}
}